/**
 * Created by Heycz on 2015/9/24.
 */
appService
  .factory('CustomersService', function ($http, CommonUtils) {

    var userInfo = {userCode: 'sie_xiaobozhi',userid:'24633248'};//从微平台读取的客户信息
    //var userInfo = null;//从微平台读取的客户信息

    var apiUrl = 'http://192.168.1.106:8080/eos-default/';
    var defaultTimeout = 3000;//默认超时时间

    var customers;//客户
    var currentCustomer;//用于记录当前操作的客户
    var currentCard;//用于记录当前操作的客户名片

    this.getUserInfo = function (callback) {
      if (!userInfo) {
        wpt.getUsersInfo(
          function (msg) {
            userInfo = angular.fromJson(msg);
            callback(userInfo);
          }, function () {
            alert('获取用户信息失败');
          });
      } else {
        callback(userInfo);
      }
    };
    this.getCustomers = function (callback) {
      if (!customers) {
        this.getAll(callback)
      } else {
        callback(customers);
      }
    };
    this.setCurrentCustomer = function (cus) {
      currentCustomer = cus;
    };
    this.getCurrentCustomer = function () {
      return currentCustomer;
    };
    this.setCurrentCard = function (card) {
      currentCard = card;
    };
    this.getCurrentCard = function () {
      return currentCard;
    };
    /**
     * 重置持有状态
     */
    this.resetState = function () {
      currentCustomer = {
        id: null,
        userid: userInfo.userCode,
        toUserId: userInfo.userCode,
        isGlobal: 0,
        cards: []
      };
      currentCard = {
        cid: null,
        cname: null,
        duty: null,
        company: null,
        phone: null,
        tel: null,
        address: null,
        dt: null
      };
    };
    this.addCardState = function () {
      currentCard = {
        cid: currentCustomer.cid,
        cname: null,
        duty: null,
        company: null,
        phone: null,
        tel: null,
        address: null,
        dt: null
      };
    };
    this.getAll = function (callback) {
      CommonUtils.showLoadingDialog('正在加载');
      $http({
        url: apiUrl + 'com.chinasie.s2c.customer.customer.getCustomerList.biz.ext',
        method: 'post',
        data: {userId: userInfo.userCode},
        timeout: defaultTimeout
      }).then(function (data) {
        if (data.data.data) {
          customers = data.data.data;
          CommonUtils.hideLoadingDialog();
          callback(customers);
        } else {
          CommonUtils.showToast('接口数据错误', 1500);
        }
      }, function () {
        CommonUtils.showToast('服务器或网络错误', 1500);
      });
    };
    /**
     * 将新建的客户添加到本地客户表中
     * @param customer
     */
    this.addCustomer = function (customer) {
      customers.push(customer);
    };
    /**
     * 获取客户名片
     * @param customer
     */
    this.loadCard = function (customer) {
      if (!customer.cards) {//如果已经加载过就不再请求
        $http({
          url: apiUrl + 'com.chinasie.s2c.customer.customer.loadCards.biz.ext',
          method: 'post',
          data: {cid: customer.cid},
          timeout: defaultTimeout
        }).success(function (data) {
          customer.cards = data.data;
        }).error(function () {
        });
      }
    };
    /**
     * 删除客户
     * @param customer
     */
    this.deleteCustomer = function (customer, success, error) {
      CommonUtils.showLoadingDialog('正在请求');
      $http({
        url: apiUrl + 'com.chinasie.s2c.customer.customer.delCustomer.biz.ext',
        method: 'post',
        data: {id: customer.cid},
        timeout: defaultTimeout
      }).success(function (data) {
        CommonUtils.hideLoadingDialog();
        if (data.result && data.result == 1) {
          var index = -1;
          for (var i = 0, n = customers.length; i < n; i++) {
            if (angular.equals(customers[i], customer)) {
              index = i;
            }
          }
          customers.splice(index, 1);
          success();
        } else {
          error();
        }
      }).error(function () {
        CommonUtils.showToast('服务器或网络错误');
      });
    };
    /**
     * 添加到收藏夹
     * @param cids
     */
    this.addToFav = function (cids, callback) {
      $http({
        url: apiUrl + 'com.chinasie.s2c.users.users.addFavorites.biz.ext',
        method: 'post',
        data: {userid: userInfo.userCode, cids: cids},
        timeout: defaultTimeout
      }).success(function (data) {
        callback(data);
      }).error(function () {
        alert('error');
      });
    };
    /**
     * 新增或更新名片
     * @param obj
     */
    this.addOrUpdateCard = function (obj, users, departments, callback) {
      CommonUtils.showLoadingDialog('正在提交');
      var tmp = [];
      if (users) {
        angular.forEach(users, function (user, index) {
          tmp.push(user.userid);
        });
        users = tmp;
      }
      obj.users = users;
      if (departments) {
        tmp = [];
        angular.forEach(departments, function (department, index) {
          tmp.push(department.depid);
        });
        departments = tmp;
      }
      obj.departments = departments;
      var data = {param: obj};
      console.log(angular.toJson(data));
      $http({
        url: apiUrl + 'com.chinasie.s2c.customer.customer.addOrUpdateCard.biz.ext',
        method: 'post',
        data: angular.toJson(data),
        timeout: defaultTimeout
      }).success(function (data) {
        CommonUtils.hideLoadingDialog();
        callback(data);
      }).error(function () {
        CommonUtils.hideLoadingDialog();
        alert('error');
      });
    };
    /**
     * 获取所有用户
     * @param callback
     */
    this.getAllUsers = function (callback) {
      CommonUtils.showLoadingDialog('正在加载');
      $http({
        url: apiUrl + 'com.chinasie.s2c.users.users.queryAllUsers.biz.ext',
        method: 'post',
        data: {userId: userInfo.userCode},
        timeout: defaultTimeout
      }).success(function (data) {
        CommonUtils.hideLoadingDialog();
        callback(data)
      }).error(function () {
        CommonUtils.showToast('服务器或网络错误');
      });
    };
    /**
     * 更新分享用户
     * @param cid
     * @param users
     * @param callback
     */
    this.updateShareUsers = function (cid, users, callback) {
      if (users) {
        var tmp = [];
        angular.forEach(users, function (user, index) {
          tmp.push(user.userid);
        });
        users = tmp;
      }
      $http({
        url: apiUrl + 'com.chinasie.s2c.users.users.updateshreUsers.biz.ext',
        method: 'post',
        data: {cid: cid, userid: users},
        timeout: defaultTimeout
      }).success(function (data) {
        callback(data);
      }).error(function (e) {

      });
    };
    /**
     * 更新分享部门
     * @param cid
     * @param departments
     * @param callback
     */
    this.updateShareDepartments = function (cid, departments, callback) {
      if (departments) {
        var tmp = [];
        angular.forEach(departments, function (department, index) {
          tmp.push(department.depid);
        });
        departments = tmp;
      }
      $http({
        url: apiUrl + 'com.chinasie.s2c.users.users.updateshareDep.biz.ext',
        method: 'post',
        data: {cid: cid, orgid: departments},
        timeout: defaultTimeout
      }).success(function (data) {
        callback(data);
      }).error(function (e) {

      });
    };
    /**
     * 获取分享用户信息
     * @param cid
     * @param callback
     */
    this.getShareInfo = function (cid, callback) {
      $http({
        url: apiUrl + 'com.chinasie.s2c.customer.customer.getShareInfo.biz.ext',
        method: 'post',
        data: {cid: cid},
        timeout: defaultTimeout
      }).success(function (data) {
        callback(data);
      }).error(function (e) {
      });
    };
    /**
     * 设置主卡片
     * @param id
     * @param cardid
     * @param callback
     */
    this.setMainCard = function (id, cardid, callback) {
      CommonUtils.showLoadingDialog("正在请求");
      $http({
        url: apiUrl + 'com.chinasie.s2c.customer.customer.setCurrentCard.biz.ext',
        method: 'post',
        data: {id: id, cardid: cardid},
        timeout: defaultTimeout
      }).success(function (data) {
        CommonUtils.hideLoadingDialog();
        if (data.result && data.result == 1) {
          callback();
        }
      }).error(function () {
        CommonUtils.showToast("服务器或网络错误");
      });
    };
    /**
     * 查询所有部门
     * @param callback
     */
    this.queryAllOrg = function (callback) {
      $http({
        url: apiUrl + 'com.chinasie.s2c.users.users.queryAllOrg.biz.ext',
        method: 'post',
        data: {userId: userInfo.userCode},
        timeout: defaultTimeout
      }).success(function (data) {
        callback(data);
      }).error(function (e) {
      });
    };
    /**
     * 转给其他同事
     * @param toUser
     * @param callback
     */
    this.giveToUser = function (toUser, callback) {
      CommonUtils.showLoadingDialog("正在请求");
      $http({
        url: apiUrl + 'com.chinasie.s2c.customer.customer.giveToUser.biz.ext',
        method: 'post',
        data: {userid: userInfo.userCode, cid: currentCustomer.cid, toUser: toUser.userid},
        timeout: defaultTimeout
      }).success(function (data) {
        CommonUtils.hideLoadingDialog();
        if (data.data && data.data == 1) {
          currentCustomer.userid = toUser.userid;
          currentCustomer.toUserId = userInfo.userCode;
          currentCustomer.cOwner = toUser.empname;
          callback();
        } else {
          CommonUtils.showToast('操作失败');
        }
      }).error(function () {
        CommonUtils.showToast("服务器或网络错误");
      });
    };
    this.setIsGlobal = function (cid, isGlobal, callback) {
      CommonUtils.showLoadingDialog("正在请求");
      $http({
        url: apiUrl + 'com.chinasie.s2c.customer.customer.setGlobal.biz.ext',
        method: 'post',
        data: {isGlobal: isGlobal, cid: cid},
        timeout: defaultTimeout
      }).success(function (data) {
        CommonUtils.hideLoadingDialog();
        callback(data);
      }).error(function () {
        CommonUtils.showToast("服务器或网络错误")
      });
    };
    this.delCard = function (cardId, callback) {
      CommonUtils.showLoadingDialog("正在请求");
      $http({
        url: apiUrl + 'com.chinasie.s2c.customer.customer.delCard.biz.ext',
        method: 'post',
        data: {cardid: cardId},
        timeout: defaultTimeout
      }).success(function (data) {
        CommonUtils.hideLoadingDialog();
        if (data.result && data.result == 1) {
          callback();
        } else {
          CommonUtils.showToast("删除名片失败");
        }
      }).error(function () {
        CommonUtils.showToast("服务器或网络错误");
      });
    };
    return this;
  });
